<?php

namespace App\Http\ManagerApi\Controllers;

use App\Api\BaseClass\Controller;
use App\Http\WechatAuth\Models\UserOrder;
use App\Http\ManagerApi\Models\User;
use App\Http\ManagerApi\Models\PlatformGoodsCategory;
use App\Http\ManagerApi\Models\PlatformGoods;

class OrderController extends Controller
{
    /**
     * 订单列表
     */
    public function listOrder()
    {
        $rules = [
            ['offset', 'required|integer'],
            ['limit', 'required|integer'],
            ['order_no', 'string'],
            ['is_send', 'integer'],
        ];

        $params = $this->form->camelFormOrFail($rules);

        $search = [
            ['where', 'order_no', 'like', '$order_no'],
            ['where', 'is_send', '$is_send'],
            ['with', 'user'],
            ['orderBy', 'id', 'desc'],
        ];

        $format = ['order_no' => '%$order_no%'];

        $datas = with(new UserOrder)->pagination($params, $search, $format);

        foreach ($datas['rows'] as $v) {
            $v->goods = json_decode($v->order_snap);
            $goods = PlatformGoods::find($v->goods->id);
            if (!isset($goods)) {
                $v->goodsCategory = null;
            } else {
                $v->goodsCategory = PlatformGoodsCategory::find($goods->primary_category_id);
            }
        }

        return $this->form->getMessage($datas);
    }

    /**
     * 订单详情
     */
    public function orderDetail()
    {
        $rules = [
            ['id', 'required|integer']
        ];

        $params = $this->form->camelFormOrFail($rules);

        $data = UserOrder::with('user')->find($params['id']);
        $data->goods = json_decode($data->order_snap);

        return $this->form->getMessage($data);
    }

    /**
     * 订单删除
     * @author yff
     * @date 2018-9-27 16:28:50
     */
    public function deleteOrder()
    {
        $rules = [
            ['id', 'required|integer']
        ];

        $params = $this->form->camelFormOrFail($rules);

        return $this->form->deleteMessage(UserOrder::destroy($params['id']));
    }

    /**
     * 发货
     * @param int $id
     * @author yff
     * @date 2018-9-27 16:32:09
     */
    public function orderSend()
    {
        $rules = [
            ['id', 'required|integer'],
            ['logistics', 'required|string'],
        ];

        $params = $this->form->camelFormOrFail($rules);

        $order = UserOrder::findOrFail($params['id']);

        $user = User::findOrFail($order->uid);

        if ($user->is_active == 0) {
            return $this->form->error('该用户未激活，不能发货');
        }

        if ($order->is_send) {
            return $this->form->error('该订单已发货');
        }

        return $this->form->updateMessage($order->update(['is_send' => 1, 'logistics' => $params['logistics']]));
    }
}